const { existsSync } = require("fs");
const { init, parseLine, stop } = require("hstack_lib");

/**
 * Stack Tracer
 */
class StackTracer {
    constructor(sourcemapFolder, namecacheFolder, libFolder) {
        this.sourcemapFolder = sourcemapFolder;
        this.namecacheFolder = namecacheFolder;
        this.libFolder = libFolder;
    }

    check() {
        if (this.sourcemapFolder && !existsSync(this.sourcemapFolder)) {
            console.log(`Error: sourcemap folder not exists: ${this.sourcemapFolder}`);
            return false;
        }
        if (this.namecacheFolder && !existsSync(this.namecacheFolder)) {
            console.log(`Error: namecache folder not exists: ${this.libFolder}`);
            return false;
        }
        if (this.libFolder && !existsSync(this.libFolder)) {
            console.log(`Error: so folder not exists: ${this.libFolder}`);
            return false;
        }
        return true;
    }

    async init() {
        if (!this.check()) {
            return false;
        }
        await init(this.sourcemapFolder || '', this.libFolder || '', this.namecacheFolder || '');
        return true;
    }

    async parseOneLine(line) {
        return await parseLine(line);
    }

    async parseMultiLines(lines) {
        let tmpLines = lines.join('\n');
        let result = await parseLine(tmpLines);
        return result.split('\n');
    }

    async unInit() {
        await stop();
    }
}

module.exports = { StackTracer };